/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.freedoit.dao;

import javax.persistence.EntityManager;
import org.apache.log4j.Logger;
import org.freedoit.exception.ServerException;
import org.freedoit.om.SyncKey;
import org.freedoit.util.LogUtils;

/**
 *
 * @author wanglei
 */
public class SyncKeyDAO {
	private static final Logger log = LogUtils.getLogger(SyncKeyDAO.class);
    public Long getKey() {
        SyncKey instance = findById(SyncKey.DEFAULT_ID);
        if (instance == null) {
            return null;
        } else {
            return instance.getKeyValue();
        }
    }
    
    public Long getClientId() {
        SyncKey instance = findById(SyncKey.DEFAULT_ID);
        if (instance == null) {
            return null;
        } else {
            return instance.getClientId();
        }
    }
    
    public void setClientId(Long clientId) {
        setSyncKey(clientId, null);
    }
    
    public void setKey(Long key) {
        setSyncKey(null, key);
    }
    
    private void setSyncKey(Long clientId, Long key) {
		EntityManager em = DAOFactory.getEntityManagerFactory().createEntityManager();
		try {
			em.getTransaction().begin();
            SyncKey instance = em.find(SyncKey.class, SyncKey.DEFAULT_ID);
            if (instance == null) {
                instance = new SyncKey();
                instance.setId(SyncKey.DEFAULT_ID);
            }
            
            if (key != null) {
                instance.setKey(key);
            }
            
            if (clientId != null) {
                instance.setClientId(clientId);
            }

			em.merge(instance);
			em.getTransaction().commit();
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw new ServerException(re);
		} finally {
			em.close();
		}
    }

	private SyncKey findById(Long id) {
		log.debug("getting TaskType instance with id: " + id);
		EntityManager em = DAOFactory.getEntityManagerFactory().createEntityManager();
		try {
			SyncKey instance = em.find(SyncKey.class, id);
			if (instance == null) {
				log.debug("get successful, no instance found");
			} else {
				log.debug("get successful, instance found");
			}
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw new ServerException(re);
		} finally {
			em.close();
		}
	}
    
}
